/*
 * Project: BoboDesignPattern
 * 
 * File Created at 2019年5月1日
 * 
 * Copyright 2012 Greenline.com Corporation Limited.
 * All rights reserved.
 *
 * This software is the confidential and proprietary information of
 * Greenline Company. ("Confidential Information").  You shall not
 * disclose such Confidential Information and shall use it only in
 * accordance with the terms of the license agreement you entered into
 * with Greenline.com.
 */
package test.lesson3.tree.binarytree;

import java.util.Arrays;

/**
 * @Type HeapSort2
 * @Desc
 * @author 52489
 * @date 2019年5月1日
 * @Version V1.0
 */
public class HeapSort2 {

    public static void main(String[] args) {
        int arr[] = { 3, 2, 1, 7, 8, 4, 6, 5 };
        for (int i = arr.length / 2 - 1; i >= 0; i--) {
            sortHeap(arr, i, arr.length);
        }

        // for (int j = arr.length - 1; j > 0; j--) {
        // swap(j, 0, arr);
        // sortHeap(arr, 0, j);
        // }
        System.out.println(Arrays.toString(arr));
    }

    /**
     * @param j
     * @param i
     * @param arr
     */
    private static void swap(int j, int i, int[] arr) {
        int tmp = arr[j];
        arr[j] = arr[i];
        arr[i] = tmp;
    }

    /**
     * @param arr
     * @param i
     * @param length
     */
    private static void sortHeap(int[] arr, int i, int length) {
        int tmp = arr[i];
        for (int k = 2 * i + 1; k < length; k = k * 2 + 1) {
            if (k + 1 < length && arr[k] < arr[k + 1]) {
                k++;
            }
            if (arr[k] > tmp) {
                arr[i] = arr[k];
                i = k;
            } else {
                break;
            }
        }
        arr[i] = tmp;
        System.out.println(Arrays.toString(arr));
    }

}
